import string

ESCAPE_CHAR = '\\'

def escape_string(mystr):
    res = ''
    for c in mystr:
        if not c in string.printable:
            res = res + ESCAPE_CHAR
            code = ord(c)
            res = res + '%02x' % code
        elif c == ESCAPE_CHAR:
            res = res + ESCAPE_CHAR + ESCAPE_CHAR
        else:
            res = res + c
    return res

def unescape_string(mystr):
    if mystr == None:
        return ""
    
    res = ''
    skipcount = 0
    for i in range(0, len(mystr)):
        if skipcount > 0:
            skipcount = skipcount - 1
            continue

        if mystr[i] == ESCAPE_CHAR:
            if mystr[i + 1] == ESCAPE_CHAR:
                res = res + ESCAPE_CHAR
                skipcount = 1
            else:
                code = int(mystr[i+1:i+3], 16)
                res += chr(code)
                skipcount = 2
        else:
            res += mystr[i]
    return res
